package com.yl.nettylearning.netty.day05;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author yangl
 */
public class Client {

    private final String host;
    private final int port;

    public Client(String host, int port){
        this.host = host;
        this.port = port;
    }

    public void run(){
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //的到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入相关的handler
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast(new ClientHandler());
                        }
                    });
            try {
                ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
                System.out.println("==========" + channelFuture.channel().localAddress() + "====准备好了==========");
                //客户端需要输入，创建一个扫描器
                Scanner scanner = new Scanner(System.in);
                while (scanner.hasNext()){
                    String msg = scanner.nextLine();
                    channelFuture.channel().writeAndFlush(msg);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }finally {
            eventExecutors.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new Client("127.0.0.1", 8888).run();
    }
}
